package com.yang.sso.oauth.controller;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.yang.sso.oauth.enums.GrentTypeEnum;
import com.yang.sso.oauth.enums.ResultCode;
import com.yang.sso.oauth.model.PwdLoginDto;
import com.yang.sso.oauth.properties.SecurityProperties;
import com.yang.sso.oauth.result.Result;
import com.yang.sso.oauth.utils.EncryptUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


/**
 * 授权/登录
 * @author: Islands
 * @create: 2024-04-12 21:59
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class AuthController{
    private final SecurityProperties clientProperties;
    private final TokenEndpoint tokenEndpoint;
    private final TokenStore tokenStore;

    protected final HttpServletRequest request;

    private final static String KEY_DES="d7b85f6e214abcde";

    /**
     * 账号密码登录(密码模式)
     * @param dto
     * @return
     */
    @PostMapping("/pwdLogin")
    public Result<?> pwdLogin(@RequestBody PwdLoginDto dto) throws HttpRequestMethodNotSupportedException{
        String password = EncryptUtil.aesDecryptForFront(dto.getPassword(), KEY_DES);
        if(StringUtils.isBlank(password)){
            return Result.failed(ResultCode.LOGIN_FAIL,"账号/密码错误");
        }
        //获取凭证
        User clientUser = new User(clientProperties.getClients()[1].getClientId(),
                clientProperties.getClients()[1].getClientSecret(), new ArrayList<>());
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(clientUser, null, new ArrayList<>());
        Map<String, String> map = new HashMap<>();
        map.put("username", dto.getUsername());
        map.put("password", password);
        map.put("grant_type", GrentTypeEnum.PASSWORD.getValue());
        OAuth2AccessToken resultToken = tokenEndpoint.postAccessToken(token, map).getBody();
        if(null!=resultToken){
            return Result.success(ResultCode.LOGIN_SUCCESS,resultToken);
        }
        return Result.failed(ResultCode.LOGIN_FAIL,"授权失败");
    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping(value = "/logout")
    public Result<?> logOut() {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null) {
            String token = authHeader.replace("Bearer", "").trim();
            OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(token);
            if (oAuth2AccessToken != null) {
                OAuth2RefreshToken oAuth2RefreshToken = oAuth2AccessToken.getRefreshToken();
                //从tokenStore中移除token
                tokenStore.removeAccessToken(oAuth2AccessToken);
                // 检查是否存在刷新令牌
                if (oAuth2AccessToken.getRefreshToken() != null) {
                    tokenStore.removeRefreshToken(oAuth2RefreshToken);
                    tokenStore.removeAccessTokenUsingRefreshToken(oAuth2RefreshToken);
                }
                return Result.success(ResultCode.SUCCESS);
            }
        }
        return Result.failed("退出成功");
    }

}
